package com.zb.baidu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zb.constant.RedisConstant;
import com.zb.exception.BaiduAppException;
import com.zb.http.HttpClientUtil;
import com.zb.redis.RedisUtil;
import com.zb.yaml.MapSecret;


/**
 * 百度密钥工具服务类
 * @Author WEN
 * @Date 2024/5/24 0024
 **/
public class BaiduKeyUtilService {
    private static final String REDIS_CACHE_PREFIX = RedisConstant.REDIS_PREFIX + ":map:";
    private static final String MAP_ACCESS_TOKEN = REDIS_CACHE_PREFIX + ":access_token:";

    /**
     * 获取请求token
     * @return
     */
    public static String getToken() throws BaiduAppException {
        if (RedisUtil.hasKey(MAP_ACCESS_TOKEN)) {
            return (String) RedisUtil.getByKey(MAP_ACCESS_TOKEN);
        }
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=" + MapSecret.getMapGrantType() + "&client_id="+ MapSecret.getMapClientId() +"&client_secret=" + MapSecret.getMapClientSecret();
        String bodyObj = HttpClientUtil.post(url);
        JSONObject obj = JSON.parseObject(bodyObj, JSONObject.class);
        mapApiResultCode(obj);
        // 提前10分钟过期
        Long expiresIn = obj.getLong("expires_in") - (10 * 60);
        String accessToken = obj.getString("access_token");
        RedisUtil.setCache(MAP_ACCESS_TOKEN, accessToken, expiresIn);
        return accessToken;
    }


    public static void mapApiResultCode(JSONObject obj) throws BaiduAppException {
        String errorCode = obj.getString("error_code");
        if (StringUtils.isBlank(errorCode)) {
            return;
        }
        switch (errorCode) {
            case "6" -> {
                throw new BaiduAppException("您没有调用权限，请到百度云官网开启权限后再重试！");
            }
            case "18" -> {
                throw new BaiduAppException("请求解析次数已达到开放上限，请检查调用量是否充足！");
            }
            case "17" -> {
                throw new BaiduAppException("今日请求解析次数已达到开放上限，请检查调用量是否充足！");
            }
        }
    }
}
